<template>
  <el-dialog :title="title" :visible.sync="visible" width="400px" :before-close="handleClose">
    <el-form ref="formData" :rules="rules" :model="formData" label-width="100px" label-position="right" style="width: 300px" status-icon>
      <el-form-item label="标签名称：" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="分类名称：" prop="categoryId">
        <el-select v-model="formData.categoryId" clearable filterable>
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="titleImg">
        <!--accept="image/png, image/jpeg" ：接收上传的类型 action 指定上传地址，但是我们不用它默认的，所以给它空的，不能把它删除，默认这个必须要有 show-file-list 是否显示已上传文件列表，因为只传一张，所以不要显示 http-request 自定义上传实现 -->
        <el-upload class="avatar-uploader"
                   action=""
                   accept="image/*"
                   :show-file-list="false"
                   :http-request="uploadMainImg">
          <img
            v-if="formData.titleImg"
            :src="formData.titleImg"
            class="avatar"
            height="100%"
            width="100%">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="submitForm('formData')">确定</el-button>
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>

import api from '@/api/label'
import commonApi from '@/api/common'

export default {
  props: {
    title: { // 弹窗的标题
      type: String,
      default: ''
    },
    visible: { // 弹出窗口，true弹出
      type: Boolean,
      default: false
    },
    formData: { // 提交表单数据
      type: Object,
      default: {}
    },
    categoryList: { // 正常状态的分类列表数据
      type: Array,
      default: []
    },
    remoteClose: Function // 用于关闭窗口
  },

  data() {
    return {
      rules: {
        name: [ // 标签名称
          {required: true, message: '请输入标签名称', trigger: 'blur'},
        ],
        categoryId: [ // 分类
          {required: true, message: '请选择分类名称', trigger: 'change'},
        ]
      }
    }
  },

  methods: {
    // 关闭弹窗
    handleClose() {
      // 表单清空
      this.$refs['formData'].resetFields()
      // 调用父组件中的方法关闭窗口
      this.remoteClose()
    },
    // 上传主图
    uploadMainImg(file) {
      // 封装表单对象
      const data = new FormData()
      data.append('file', file.file)
      // 发送请求上传
      commonApi.uploadImg(data).then(response => {
        this.$message.success('上传成功')
        this.formData.titleImg = response.data
      }).catch(() => {
        this.$message.error('上传失败')
      })
    },
    // 提交表单数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过，提交表单数据
          this.submitData()
        } else {
          // console.log('error submit!!');
          return false;
        }
      })
    },

    // 调用接口提交数据
    async submitData() {
      let response = null

      if (this.formData.id) {
        // 编辑
        response = await api.update(this.formData)
      } else {
        // 新增
        response = await api.add(this.formData)
      }

      if (response.code === 20000) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        // 关闭窗口
        this.handleClose()
      } else {
        this.$message({
          message: '保存失败',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #9a9a9a;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  max-width: 260px;
  max-height: 150140;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 140px;
  line-height: 140px;
  text-align: center;
}

.avatar {
  width: 100%;
  display: block;
}
</style>
